package com.android.component;

import com.utils.LogUtil;
import com.utils.ThreadWithHandler;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class ThreadWithHandlerTest extends Activity implements OnClickListener {
    private static final String TAG = "ThreadWithHandlerTest";

    TextView tvlog;

    ThreadWithHandler thread;
    Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.thread_with_handler);

        tvlog = (TextView) findViewById(R.id.tvlog);
        LogUtil.setTv(tvlog);

        findViewById(R.id.sen_msg).setOnClickListener(this);
        findViewById(R.id.post_runnable).setOnClickListener(this);
        findViewById(R.id.start).setOnClickListener(this);
        findViewById(R.id.stop).setOnClickListener(this);

        LogUtil.d(TAG, "主线程id是：" + Thread.currentThread().getId());

    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.sen_msg) {
            thread.sendEmptyMessage(1);
        } else if (v.getId() == R.id.post_runnable) {
            thread.post(new Runnable() {
                @Override
                public void run() {
                    LogUtil.e(TAG, "runnable所在线程是：" + Thread.currentThread().getId());
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });

            handler.post(new Runnable() {
                @Override
                public void run() {
                    LogUtil.e(TAG, "activity中的runnable所在线程是：" + Thread.currentThread().getId());
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        } else if (v.getId() == R.id.start) {
            thread = new ThreadWithHandler();
            thread.start();
        } else if (v.getId() == R.id.stop) {
            thread.interrupt();
//            thread = null;
        }

    }

}
